package com.gsp.gspframework.servlet;

import com.google.gson.Gson;
import com.gsp.gspframework.bean.Data;
import com.gsp.gspframework.bean.Handler;
import com.gsp.gspframework.bean.Param;
import com.gsp.gspframework.bean.View;
import com.gsp.gspframework.helper.*;
import com.gsp.gspframework.util.ReflectionUtil;
import com.gsp.gspframework.util.StreamUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {

    private final static Gson gson = new Gson();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestMethod = req.getMethod().toLowerCase();
        String requestPath = req.getPathInfo();
        if ("/favicon.ico".equals(requestPath)) {
            return;
        }
        Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
        if (handler != null) {
            Class<?> controllerClass = handler.getControllerClass();
            Object controllerBean = BeanHelper.getBean(controllerClass);

            Param param;
            if (UploadHelper.isMultipart(req)) {
                param = UploadHelper.createParam(req);
            } else {
                param = RequestHelper.createParam(req);
            }

            Method actionMethod = handler.getMethod();
            Object result = ReflectionUtil.invoke(controllerBean, actionMethod, param);
            if (result instanceof View) {
                handleViewResult(req, resp, (View) result);
            } else if (result instanceof Data) {
                handleDataResult(resp, (Data) result);
            }
        }
    }

    private void handleDataResult(HttpServletResponse resp, Data result) throws IOException {
        Object model = result.getModel();
        if (model != null) {
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            PrintWriter pw = resp.getWriter();
            String json = gson.toJson(model);
            pw.write(json);
            pw.flush();
            pw.close();
        }
    }

    private void handleViewResult(HttpServletRequest req, HttpServletResponse resp, View view) throws IOException, ServletException {
        String path = view.getPath();
        if (path.startsWith("/")) {
            resp.sendRedirect(req.getContextPath() + path);
        } else {
            Map<String, Object> model = view.getModel();
            model.entrySet().stream().forEach(entry -> req.setAttribute(entry.getKey(), entry.getValue()));
            req.getRequestDispatcher(ConfigHelper.getAppJspPath() + path).forward(req, resp);
        }
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        LoadHelper.init();
        ServletContext servletContext = config.getServletContext();
        ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
        jspServlet.addMapping(ConfigHelper.getAppJspPath() + "*");
        ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
        defaultServlet.addMapping(ConfigHelper.getAppAssetPath() + "*");
        UploadHelper.init(servletContext);
    }
}
